<?php
session_start();  //启动会话
//如果未登录，没有设置session变量“stuNo”，跳转到登录页
if (!isset($_SESSION['stuNo'])) {
    header('Location:Login.php?frompage=Results');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩查询</title>
</head>
<body>
    <?php
    include 'HeaderNav.html';
    ?>
    <h1>成绩查询</h1>
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
    学号:<input type="text" name="stuNo"/>
    <input type="submit" name="btnSubmit" value="查询"/>
</form>

<!-- 检查学号文本框数据，如果为空或者不是有效学号，弹出提示框，终止表单提交 -->
<script type="text/javascript">       
var elform = document.getElementsByTagName("form")[0];//获取表单
elform.onsubmit=function(){
    //表单提交，检查学号文本框的数据
       
    var elStuNo =  document.getElementsByName("stuNo")[0];//获取学号文本框
    var regexStuNo = /\d{8}/;//验证规则为8位数字
    if(elStuNo.value==""||!regexStuNo.test(elStuNo.value)){
        window.alert("请输入有效的学号!");
        return false; //终止表单提交
    }
}


</script>

<?php
if(isset($_POST["btnSubmit"])){
    //用户输入的学号
    $stuNo=$_POST["stuNo"];
    echo "<script> document.getElementsByName('stuNo')[0].value='{$stuNo}' </script>";
    
    require_once 'Conn.php';
    
    $db->query("SET NAMES utf8");

    $sql= "SELECT Result.StudentID,Result.Mark,Course.CourseName,Student.StudentName FROM Result INNER JOIN Student ON Result.StudentID=Student.StudentID INNER JOIN Course ON Result.CourseID=Course.CourseID WHERE Student.StudentID='$stuNo'";
    //执行查询
    $result = mysqli_query($db,$sql);
    if($result = mysqli_query($db,$sql)){
        echo"<table class='tb'><tr><th>姓名</th><th>课程名称</th><th>成绩</th></tr>";
        //获取数据
        while ($row = $result->fetch_assoc()){
            echo"<tr><td>".$row["StudentName"].
            "</td><td>".$row["CourseName"].
            "</td><td>".$row["Mark"].
            "</td></tr>";
        }
        echo "</table>";
    }
    //没有查询到记录
    else{
        echo "<div style='color:red;margin-top:50px;'>没有该生的成绩记录!</div>";

    }
    //释放结果集
    $result->close();
    //关闭连接
    $db->close();
}
?>

<?php
include 'Footer.html';//包含页脚页
?>
</body>
</html>